package cn.newgrand.netcall.consultant.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.component.VerticalFlowLayout;
import org.jivesoftware.spark.ui.ChatRoom;
import org.jivesoftware.spark.ui.ChatRoomNotFoundException;

import cn.newgrand.common.NetcallUtil;
import cn.newgrand.netcall.consultant.SpecialistQueueManager;
import cn.newgrand.smackx.consultant.ConsultantManager;

public class MessageCenterPanel extends JPanel {
	
    public static final Cursor HAND_CURSOR = new Cursor(Cursor.HAND_CURSOR);

    public static final Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR);
	
	private Map<String,JPanel> map = new HashMap<String,JPanel>();
	
	private static MessageCenterPanel me;
	
	private int leaveTime = 30;
	
	public int getLeaveTime() {
		return leaveTime;
	}

	public void setLeaveTime(int leaveTime) {
		this.leaveTime = leaveTime;
	}

	public boolean isHasSpecialistMessage(String spid){
		return map.containsKey(spid);
	}
	
	public JoinMessageItem getJoinMessageItem(String spid){
		if(isHasSpecialistMessage(spid)){
			return (JoinMessageItem)map.get(spid);
		}
		return null;
	}
	
	public void addJoinMessageItem(String showMessage,String spjid,String spid){
		JoinMessageItem item = new JoinMessageItem(showMessage, spjid, spid);
		add(item,BorderLayout.NORTH);
		validate();
		map.put(spid, item);
	}
	
	public void removeJoinMessageItem(String spid,String spjid) {
		if(map.containsKey(spid)){
			JoinMessageItem panel = (JoinMessageItem)map.get(spid);
			ChatRoom room;
			try {
				String spBarejid = StringUtils.parseBareAddress(spjid);
				room = SparkManager.getChatManager().getChatContainer().getChatRoom(spBarejid);
				SparkManager.getChatManager().getChatContainer().closeChatRoom(room);
//				map.remove(spid);
//				ConsultantManager.getInstance(SparkManager.getConnection()).sendConversationOver(spid);
			} catch (ChatRoomNotFoundException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
			ConsultantManager.getInstance(SparkManager.getConnection()).sendConversationOver(spid);
			SpecialistQueueManager.getInstance().removeWhenLeave(spid);
			remove(panel);
			validate();
			map.remove(spid);
		}
	}
	
	public MessageCenterPanel(){
		initializeComponent();
        setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, false));
        setBorder(null);
        setSize(new Dimension(0, 0));
//		JLabel label = new JLabel("消息");
//		add(label);
	}
	
	public static MessageCenterPanel getInstance(){
		if(me==null){
			me =new MessageCenterPanel();
		}
		return me;
	}
	
 	private void initializeComponent(){
 		
	}
	
	public class JoinMessageItem extends JPanel{
		

		private JLabel label;
		private JLabel joinButton;
		private JLabel cancelButton;
		private JButton joinBtn;
		private JButton cancelBtn;
		private String spjid;
		private String spid;
		private JLabel leaveTimeLabel;
		private Timer timer;
		private boolean isStart = false;
		private MouseListener mouseAdapter;
		public boolean isStart() {
			return isStart;
		}

		public JoinMessageItem(String showMessage,String spjid,String spid){
			this.spjid = NetcallUtil.getBareJID(spjid);
			this.spid = spid;
			initializeComponent(showMessage);
			setLayout(new FlowLayout());
			//setPreferredSize(new Dimension(0, 20));
			this.add(label);
			this.add(joinBtn);
			this.add(cancelBtn);
			//this.add(joinButton);
			//this.add(cancelButton);
			this.add(leaveTimeLabel);
		}
		
		public void flagStarted(){
			if(!isStart){
                isStart = true;
                timer.cancel();
                leaveTimeLabel.setVisible(false);
                ConsultantManager.getInstance(SparkManager.getConnection()).sendConversationStart(spid);
            }
		}
		
		private void startTimer(){
			timer = new Timer("awake Timer",true);
			TimerTask task = new TimerTask() {
				int i = getLeaveTime();
				@Override
				public void run() {
					if(i > 0){
						leaveTimeLabel.setText(--i+"秒后自动结束");
					}else{
						timer.cancel();
					}
				}
			};
			timer.schedule(task, 1000, 1000);
		}
		
		private void initializeComponent(String showMessage){
			String trueName = ConsultantManager.getInstance(SparkManager.getConnection()).getRoster().getEntry(spid).getTruename();
			if(!"".equals(trueName) && trueName != null){
				label = new JLabel("专家:"+trueName);
			}else{
				label = new JLabel(showMessage);
			}
			//label = new JLabel(showMessage);
			joinBtn = new JButton(" 开始 ");
			joinBtn.setBorder(BorderFactory.createEmptyBorder(1,1, 1, 1));
			cancelBtn = new JButton(" 结束 ");
			cancelBtn.setBorder(BorderFactory.createEmptyBorder(1,1, 1, 1));
			joinButton = new JLabel("<html><u>"+"开始"+"</u></html>");
			cancelButton = new JLabel("<html><u>"+"结束"+"</u></html>");
			leaveTimeLabel = new JLabel("30秒后自动结束");
			startTimer();
			joinBtn.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					ChatRoom chatRoom = SparkManager.getChatManager().createChatRoom(spjid, spid, spid);
                    SparkManager.getChatManager().getChatContainer().activateChatRoom(chatRoom);
//                    if(!isStart){
//                        isStart = true;
//                        timer.cancel();
//                        leaveTimeLabel.setVisible(false);
//                        ConsultantManager.getInstance(SparkManager.getConnection()).sendConversationStart(spid);
//                    }
                    flagStarted();
				}
			});
			cancelBtn.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent e) {
					int result = JOptionPane.showConfirmDialog(SparkManager.getMainWindow(), "确定要退出吗？", "提示", JOptionPane.YES_NO_OPTION);
					if(result==JOptionPane.YES_OPTION){
						try {
							ChatRoom room = SparkManager.getChatManager().getChatContainer().getChatRoom(spjid);
							SparkManager.getChatManager().getChatContainer().closeChatRoom(room);
	
						} catch (ChatRoomNotFoundException e1) {
							// TODO Auto-generated catch block
							//e1.printStackTrace();
						}
						ConsultantManager.getInstance(SparkManager.getConnection()).sendConversationOver(spid);
						SpecialistQueueManager.getInstance().removeWhenLeave(spid);
						MessageCenterPanel.getInstance().remove(JoinMessageItem.this);//无法解决不失去焦点就无法重绘问题，用JOptionPane来破坏焦点
						map.remove(spid);
					}
				}
			});
			mouseAdapter = new MouseAdapter() {
				@Override
				public void mouseEntered(MouseEvent e) {
					// TODO Auto-generated method stub
	                setCursor(HAND_CURSOR);
				}

				@Override
				public void mouseExited(MouseEvent e) {
					// TODO Auto-generated method stub
	                setCursor(DEFAULT_CURSOR);
				}
			};
			cancelBtn.addMouseListener(mouseAdapter);
			joinBtn.addMouseListener(mouseAdapter);
			joinButton.addMouseListener(new MouseAdapter(){

				@Override
				public void mouseClicked(MouseEvent e) {
					// TODO Auto-generated method stub
                    ChatRoom chatRoom = SparkManager.getChatManager().createChatRoom(spjid, spid, spid);
                    SparkManager.getChatManager().getChatContainer().activateChatRoom(chatRoom);
//                    if(!isStart){
//                        isStart = true;
//                        timer.cancel();
//                        leaveTimeLabel.setVisible(false);
//                        ConsultantManager.getInstance(SparkManager.getConnection()).sendConversationStart(spid);
//                    }
                    flagStarted();
				}

				@Override
				public void mouseEntered(MouseEvent e) {
					// TODO Auto-generated method stub
					joinButton.setForeground(new Color(0,0,255));
					joinButton.setText("<html><u>"+"开始"+"</u></html>");
				}

				@Override
				public void mouseExited(MouseEvent e) {
					// TODO Auto-generated method stub
					joinButton.setForeground(new Color(0,0,0));
					joinButton.setText("<html><u>"+"开始"+"</u></html>");
				}
				
			});
			
			joinButton.addMouseListener(new MouseAdapter(){
				@Override
				public void mouseEntered(MouseEvent e) {
					// TODO Auto-generated method stub
	                setCursor(HAND_CURSOR);
				}

				@Override
				public void mouseExited(MouseEvent e) {
					// TODO Auto-generated method stub
	                setCursor(DEFAULT_CURSOR);
				}
			});
				
			cancelButton.addMouseListener(new MouseAdapter(){

				@Override
				public void mouseClicked(MouseEvent e) {
					// TODO Auto-generated method stub
					int result = JOptionPane.showConfirmDialog(SparkManager.getMainWindow(), "确定要退出吗？", "提示", JOptionPane.YES_NO_OPTION);
					if(result==JOptionPane.YES_OPTION){
						try {
							ChatRoom room = SparkManager.getChatManager().getChatContainer().getChatRoom(spjid);
							SparkManager.getChatManager().getChatContainer().closeChatRoom(room);
	
						} catch (ChatRoomNotFoundException e1) {
							// TODO Auto-generated catch block
							//e1.printStackTrace();
						}
						ConsultantManager.getInstance(SparkManager.getConnection()).sendConversationOver(spid);
						SpecialistQueueManager.getInstance().removeWhenLeave(spid);
						MessageCenterPanel.getInstance().remove(JoinMessageItem.this);//无法解决不失去焦点就无法重绘问题，用JOptionPane来破坏焦点
						map.remove(spid);
					}
				}

				@Override
				public void mouseEntered(MouseEvent e) {
					// TODO Auto-generated method stub
					cancelButton.setForeground(new Color(0,0,255));
					cancelButton.setText("<html><u>"+"结束"+"</u></html>");
				}

				@Override
				public void mouseExited(MouseEvent e) {
					// TODO Auto-generated method stub
					cancelButton.setForeground(new Color(0,0,0));
					cancelButton.setText("<html><u>"+"结束"+"</u></html>");
				}
				
			});
			
			cancelButton.addMouseListener(new MouseAdapter(){
				@Override
				public void mouseEntered(MouseEvent e) {
					// TODO Auto-generated method stub
	                setCursor(HAND_CURSOR);
				}

				@Override
				public void mouseExited(MouseEvent e) {
					// TODO Auto-generated method stub
	                setCursor(DEFAULT_CURSOR);
				}
			});
		}
		
	}
}
